import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import '../widgets/other_user_header.dart';
import 'other_user_works_tab.dart';
import 'other_user_likes_tab.dart';
import 'user_chat_page.dart';
import '../../../core/providers/global_state_coordinator.dart';
import '../../../core/utils/app_utils.dart';

/// 他人用户详情页面
class OtherUserPage extends StatefulWidget {
  final String userId;

  const OtherUserPage({super.key, required this.userId});

  @override
  State<OtherUserPage> createState() => _OtherUserPageState();
}

class _OtherUserPageState extends State<OtherUserPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  @override
  bool get wantKeepAlive => true;

  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 2,
      vsync: this,
      animationDuration: const Duration(milliseconds: 200),
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/my-bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: NestedScrollView(
          headerSliverBuilder: (context, innerBoxIsScrolled) {
            return [
              SliverToBoxAdapter(
                child: OtherUserHeader(
                  userId: widget.userId,
                  onBackTap: _handleBackTap,
                ),
              ),
              SliverToBoxAdapter(child: _buildChatButtonSection()),
              SliverToBoxAdapter(child: _buildTabSection()),
            ];
          },
          body: TabBarView(
            controller: _tabController,
            physics: const ClampingScrollPhysics(),
            children: [
              OtherUserWorksTab(userId: widget.userId),
              OtherUserLikesTab(userId: widget.userId),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTabSection() {
    return Container(
      padding: EdgeInsets.only(left: 16.w, top: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          _buildTabOption('Works', 0),
          SizedBox(width: 40.w),
          _buildTabOption('Likes', 1),
        ],
      ),
    );
  }

  Widget _buildTabOption(String title, int index) {
    return GestureDetector(
      onTap: () {
        _tabController.animateTo(index);
        setState(() {});
      },
      child: AnimatedBuilder(
        animation: _tabController,
        builder: (context, child) {
          final isActive = _tabController.index == index;

          return Column(
            children: [
              Text(
                title,
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w700,
                  color:
                      isActive
                          ? Colors.white
                          : Colors.white.withValues(alpha: 0.6),
                  fontFamily: 'Poppins',
                ),
              ),

              SizedBox(height: 2.h),

              Container(
                width: 6.w,
                height: 6.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: isActive ? Colors.white : Colors.transparent,
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  /// 构建聊天按钮区域
  Widget _buildChatButtonSection() {
    return Container(
      padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 10.w),
      child: Center(
        child: GestureDetector(
          onTap: _handleChatTap,
          child: Container(
            width: 167.w,
            height: 54.h,
            decoration: BoxDecoration(
              image: const DecorationImage(
                image: AssetImage('assets/images/chat-button.png'),
                fit: BoxFit.contain,
              ),
              borderRadius: BorderRadius.circular(8.r),
            ),
          ),
        ),
      ),
    );
  }

  /// 处理聊天按钮点击
  void _handleChatTap() {
    final coordinator = context.read<GlobalStateCoordinator>();

    // 检查用户是否登录
    if (!coordinator.isLoggedIn) {
      AppUtils.showLoginRequired(
        context,
        message: 'Please login to start a chat',
        onLogin: () {
          Navigator.pushNamed(context, '/login');
        },
      );
      return;
    }

    // 跳转到聊天页面
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => UserChatPage(userId: widget.userId),
      ),
    );
  }

  /// 处理返回按钮点击
  void _handleBackTap() {
    Navigator.of(context).pop();
  }
}
